import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/config/config.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

class DioHttp {
  late Dio _client;
  BuildContext? context;
  static DioHttp of(BuildContext context) {
    return DioHttp._internal(context);
  }

  DioHttp._internal(context) {
    if (context != this.context) {
      this.context = context;
      BaseOptions options = BaseOptions(
          baseUrl: Config.baseUrl,
          connectTimeout: 1000 * 100,
          receiveTimeout: 1000 * 3,
          extra: {'context': context});
      Dio client = Dio(options);
      _client = client;
    }
  }

  Future<Response<Map<String, dynamic>>> get(
    String path, [
    Map<String, dynamic>? params,
    String? token,
  ]) async {
    Options requestOptions = Options(headers: {'Authorization': token});
    return await _client.get(path,
        queryParameters: params, options: requestOptions);
  }

  Future<Response<Map<String, dynamic>>> post(
    String path, [
    Map<String, dynamic>? params,
    String? token,
  ]) async {
    Options requestOptions = Options(headers: {'Authorization': token});
    return await _client.post(path, data: params, options: requestOptions);
  }

  Future<Response<Map<String, dynamic>>> delete(
    String path, [
    Map<String, dynamic>? params,
    String? token,
  ]) async {
    Options requestOptions = Options(headers: {'Authorization': token});
    return await _client.delete(path, data: params, options: requestOptions);
  }

  Future<Response<Map<String, dynamic>>> postFormData(
    String path, [
    FormData? params,
    String? token,
  ]) async {
    Options requestOptions = Options(
        headers: {'Authorization': token}, contentType: 'multipart/form-data');
    return await _client.post(path, data: params, options: requestOptions);
  }
}
